﻿using System;
using System.Net;
using System.Text;
using System.Linq;
using System.Collections.Generic;

namespace SNSpirit.Helpers
{
    public static class WebHelper
    {
        public static string GetDomain(this Uri uri)
        {
            if (uri == null)
                throw new ArgumentNullException("uri");
            
            var host = uri.Host;

            int dotCount = 0;
            int i = host.Length - 1;

            for(; i >=0 ; i--)
                if (host[i] == '.')
                {
                    dotCount++;
                    if (dotCount == 2)
                    {
                        i++;
                        break;
                    }
                }

            return host.Substring(i);
        }

        public static Dictionary<string,string> GetUriQueryDictionary(this Uri uri)
        {
            if (uri == null)
                throw new ArgumentNullException("uri");

            Dictionary<string, string> dict = new Dictionary<string, string>();

            var uriStr = uri.ToString();
            string queryStr = null;

            var qIndex = uriStr.IndexOf('?');
            var sIndex = uriStr.IndexOf('#');

            if (qIndex == -1 && sIndex == -1)
                return dict;
            else if (qIndex == -1 && sIndex != -1)
                queryStr = uriStr.Substring(sIndex + 1);
            else if (qIndex != -1 && sIndex == -1)
                queryStr = uriStr.Substring(qIndex + 1);
            else
                queryStr = uriStr.Substring(Math.Min(qIndex, sIndex) + 1);

            foreach (var seg in queryStr.Split('&'))
            {
                var queryPair = seg.Split('=');
                dict[queryPair[0]] = queryPair[1];
            }

            return dict;
        }

        public static string ComposeUrlQuery(Dictionary<string, string> arg)
        {
            if (arg == null)
                throw new ArgumentNullException("arg");

            StringBuilder sBuilder = new StringBuilder();

            if (arg.Count != 0)
            {
                foreach (var x in arg)
                    sBuilder.Append(string.Format("{0}={1}&", x.Key, x.Value));
                return sBuilder.ToString(0, sBuilder.Length - 1);
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Get cookie collection from cookie string
        /// NOTE: expires not support yet
        /// </summary>
        /// <param name="cookieString"></param>
        /// <returns></returns>
        public static CookieCollection GetCookieCollection(string cookieString)
        {
            if (string.IsNullOrWhiteSpace(cookieString))
                throw new ArgumentException("cookieString");

            var cookiePieces = cookieString.Split(';').Select(p => p.Trim());

            CookieCollection cookies = new CookieCollection();

            foreach (var piece in cookiePieces)
            {
                // ingore expires
                if (piece.Contains("expires"))
                    continue;

                var segs = piece.Split(',').Select(p => p.Trim());

                string name = null, value = null, path = null;

                foreach (var x in segs)
                {
                    int eIndex = x.IndexOf('=');
                    if (eIndex == -1)
                        throw new ArgumentException("Invalid cookie string format. Cannot find '='");

                    string key = x.Substring(0, eIndex);

                    if (string.Compare(key, "path", true) == 0)
                    {
                        if (eIndex < x.Length - 1)
                            path = x.Substring(eIndex + 1, x.Length - eIndex - 1);
                    }
                    else
                    {
                        name = key;
                        value = string.Empty;
                        if (eIndex < x.Length - 1)
                            value = x.Substring(eIndex + 1, x.Length - eIndex - 1);
                    }
                }

                if(name != null && value != null)
                    cookies.Add(path != null ? new Cookie(name, value, path) : new Cookie(name, value));
            }

            return cookies;
        }
    }
}
